<?php


namespace common\helpers;


use yii\helpers\FileHelper;

class Tool
{


    // protected static $data;

    public static function getIP()
    {
        return ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
    }

    public static function getTime()
    {
        // if (is_null(static::$data['date'])) {
        //     static::$data['date'] = date('Y-m-d H:i:s');
        // }
        return date('Y-m-d H:i:s', time());
    }

    public static function getCodeByDate(\yii\db\ActiveRecord $record, $prefix = '')
    {
        $maxId = $record->find()->max('id') + 1;
        return sprintf('%1$s%2$s%3$d', $prefix, date("Ymd"), $maxId);
    }

    public static function getCode($prefix = '')
    {
        return sprintf('%1$s%2$s%3$d', $prefix, date("Ymd"), time());
    }

    /**
     * 计算年龄精准到年月日
     * @param type $birthday
     * @return array
     */

    public static function calAge($birthday)
    {
        list($by, $bm, $bd) = explode('-', $birthday);
        $cm = date('n');
        $cd = date('j');
        $age = date('Y') - $by - 1;
        if ($cm > $bm || $cm = $bm && $cd > $$bd) $age++;
        return $age;
    }


    public static function saveBase64($data)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $data, $result)) {
            $type = $result[2];
            $dir = date('Ymd', time());
            $logicPath = "web/uploads/$dir/";
            $storePath = \Yii::getAlias('@frontend') . '/' . $logicPath;
            if (FileHelper::createDirectory($storePath)) {
                $filename = time() . rand(0, 9999) . ".$type";
                $filePath = $storePath . $filename;
                $logicFilePath = $logicPath . $filename;
                if (file_put_contents($filePath, base64_decode(str_replace($result[1], '', $data)))) {
                    $oss = \Yii::$app->get('oss');
                    $oss->upload($logicFilePath, $filePath);
                    @\unlink($filePath);
                    return $logicFilePath;
                }
            }
        }
        return null;
    }

    public static function curlPost($url, $data)
    {

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data),
            'Authorization: Bearer ' . \Yii::$app->params['token']
        ));

        $result = curl_exec($ch);
        if ($result) {
            return $result;
        }
        return null;
    }

    public static function curlGet($url, $data = [])
    {

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . \Yii::$app->params['token']
        ));

        $result = curl_exec($ch);
        if ($result) {
            return $result;
        }
        return null;
    }

    /** php 发送流文件
     * @param $file_name String $url 接收的路径
     * @param $file_dir String $file 要发送的文件
     * @return boolean
     */
    public static function sendStreamFile($file_name, $file_dir)
    {
        //检查文件是否存在
        if (!file_exists($file_dir . $file_name)) {
            echo "文件找不到";
            exit ();
        } else {
            //打开文件
            $file = fopen($file_dir . $file_name, "r");
            //输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: " . filesize($file_dir . $file_name));
            Header("Content-Disposition: attachment; filename=" . $file_name);
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file, filesize($file_dir . $file_name));
            fclose($file);
            exit ();
        }
    }

}